# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.name = "中信保诚「小棉袄」个人医疗保险"
        self.mysql = MysqlClient()

    def genProductInfo(self):
        plan = {

            "planA": {
                "year": [str(i) for i in range(0, 46)],
                "socialSec": ["Y", "N"],
                "expire": ["1年"],
                "payType": ["年交"],
                "money": ["2000000"]

            },
            "planB": {
                "year": [str(i) for i in range(46, 61)],
                "socialSec": ["Y", "N"],
                "expire": ["1年"],
                "payType": ["年交"],
                "money": ["1200000"]

            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["money"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    def requestJson(self, dt=None, mysql=None):
        params = '''
        productCode: XAN
        planCode: XANM001
        insuredTime: 1Y
        age: 21
        riskCode: XAN1
        dutyCode: XAN100
        amount: 200WY
        quoteno: S1588819840786194624
        '''
        data = Helper.perfectJson(params)
        data["age"] = dt["year"]
        if dt["money"] == "2000000":
            data["dutyCode"] = "XAN100" if dt["socialSec"] == "Y" else "XAN000"
            data["riskCode"] = "XAN0" if dt["socialSec"] == "N" else "XAN1"
            data["amount"] = str(int(int(dt["money"]) / 10000)) + "WY"



        else:
            data["riskCode"] = "XAN2" if dt["socialSec"] == "N" else "XAN3"
            data["amount"] = str(int(int(dt["money"]) / 10000)) + "WY"
            data["dutyCode"] = "XAN300" if dt["socialSec"] == "Y" else "XAN200"

        payload = urlencode(data).replace("+", "")

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200 and r.json()["quoteResult"]["premium"] != "0.00":
            price = r.json()["quoteResult"]["premium"]
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格更新失败:%d*/" % dt["id"])
